<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Excel文件上传解析系统</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
        }

        body {
            background: linear-gradient(135deg, #0f2027, #203a43, #2c5364);
            color: #f0f8ff;
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        header {
            text-align: center;
            margin-bottom: 30px;
            padding-top: 20px;
        }

        header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
            background: linear-gradient(90deg, #00c9ff, #92fe9d);
            -webkit-background-clip: text;
            background-clip: text;
            color: transparent;
            display: inline-block;
        }

        header p {
            font-size: 1.1rem;
            color: #a9c9ff;
            max-width: 600px;
            margin: 0 auto;
        }

        .section {
            background: rgba(16, 22, 58, 0.6);
            backdrop-filter: blur(10px);
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.36);
            border: 1px solid rgba(255, 255, 255, 0.1);
        }

        .form-wrapper {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 25px;
        }

        .upload-section {
            grid-column: 1 / -1;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .input-group {
            display: flex;
            flex-direction: column;
            margin-bottom: 20px;
            width: 100%;
        }

        .input-group label {
            font-size: 0.95rem;
            margin-bottom: 8px;
            color: #64b5f6;
            font-weight: 500;
        }

        .input-group input {
            background: rgba(255, 255, 255, 0.08);
            border: 1px solid rgba(100, 181, 246, 0.3);
            border-radius: 8px;
            padding: 12px 15px;
            font-size: 1rem;
            color: white;
            transition: all 0.3s ease;
        }

        .input-group input:focus {
            outline: none;
            border-color: #64b5f6;
            box-shadow: 0 0 0 2px rgba(100, 181, 246, 0.2);
            background: rgba(255, 255, 255, 0.12);
        }

        .drag-area {
            width: 100%;
            height: 250px;
            border: 3px dashed #4a6583;
            border-radius: 15px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-top: 10px;
            position: relative;
            overflow: hidden;
        }

        .drag-area:hover, .drag-area.active {
            border-color: #64b5f6;
            background: rgba(36, 61, 120, 0.3);
        }

        .drag-area .icon {
            font-size: 60px;
            color: #64b5f6;
            margin-bottom: 15px;
            transition: all 0.3s ease;
        }

        .drag-area.active .icon {
            transform: translateY(-10px);
        }

        .drag-area h3 {
            font-size: 1.3rem;
            font-weight: 500;
            margin-bottom: 10px;
            color: #e0f7fa;
        }

        .drag-area span {
            font-size: 0.9rem;
            color: #a3c5e7;
            max-width: 80%;
            margin: 0 auto;
        }

        .drag-area input {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
            cursor: pointer;
        }

        .file-preview {
            margin-top: 20px;
            text-align: center;
            display: none;
        }

        .file-preview.show {
            display: block;
        }

        .file-preview img {
            max-width: 180px;
            border-radius: 8px;
            margin-top: 10px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
        }

        .btn-upload {
            background: linear-gradient(90deg, #00c9ff, #92fe9d);
            border: none;
            border-radius: 8px;
            color: #15274b;
            padding: 14px 28px;
            font-size: 1.1rem;
            font-weight: 600;
            cursor: pointer;
            margin-top: 20px;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
            width: 200px;
        }

        .btn-upload:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }

        .btn-upload:hover:not(:disabled) {
            transform: translateY(-3px);
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
        }

        .progress-container {
            width: 100%;
            max-width: 500px;
            background: rgba(255, 255, 255, 0.08);
            border-radius: 8px;
            height: 10px;
            margin: 25px auto;
            overflow: hidden;
            display: none;
        }

        .progress-bar {
            height: 100%;
            background: linear-gradient(90deg, #00c9ff, #92fe9d);
            width: 0%;
            border-radius: 8px;
            transition: width 0.3s ease;
        }

        .response-message {
            text-align: center;
            padding: 15px;
            border-radius: 8px;
            margin: 15px 0;
            display: none;
        }

        .response-message.success {
            background: rgba(46, 204, 113, 0.2);
            border: 1px solid rgba(46, 204, 113, 0.5);
            display: block;
        }

        .response-message.error {
            background: rgba(231, 76, 60, 0.2);
            border: 1px solid rgba(231, 76, 60, 0.5);
            display: block;
        }

        /* Excel表格样式 */
        .excel-container {
            overflow: hidden;
            border-radius: 12px;
            border: 1px solid rgba(255, 255, 255, 0.1);
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.25);
            background: rgba(30, 30, 46, 0.7);
            display: none;
            margin-top: 20px;
        }

        .excel-container.show {
            display: block;
        }

        .excel-viewer {
            overflow-x: auto;
            max-height: 500px;
        }

        .sticky-header {
            position: sticky;
            top: 0;
            z-index: 10;
        }

        table {
            border-collapse: collapse;
            width: 100%;
            min-width: fit-content;
            background: rgba(30, 30, 46, 0.7);
            position: relative;
        }

        th {
            background: rgba(41, 59, 109, 0.95);
            padding: 16px 12px;
            text-align: left;
            color: #5dceff;
            font-weight: 600;
            border-right: 1px solid rgba(255, 255, 255, 0.1);
            user-select: none;
            white-space: nowrap;
        }

        th:last-child {
            border-right: none;
        }

        td {
            padding: 12px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.08);
            color: #d3eaff;
            max-width: 400px;
            word-wrap: break-word;
            white-space: normal;
        }

        tr:nth-child(even) td {
            background: rgba(31, 41, 64, 0.4);
        }

        tr:hover td {
            background: rgba(59, 130, 246, 0.15);
        }

        .actions {
            display: flex;
            justify-content: center;
            margin-top: 20px;
            gap: 15px;
        }

        .download-btn {
            background: linear-gradient(90deg, #3498db, #1abc9c);
            border: none;
            color: white;
            padding: 12px 25px;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s ease;
        }

        .download-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
        }

        footer {
            text-align: center;
            padding: 30px 0;
            font-size: 0.9rem;
            color: #8cb3d9;
            margin-top: 20px;
        }

        .sheet-selector {
            display: flex;
            margin-bottom: 15px;
            justify-content: center;
            gap: 10px;
            flex-wrap: wrap;
        }

        .sheet-btn {
            background: rgba(65, 105, 225, 0.25);
            color: #a3c5ff;
            border: 1px solid #4169e1;
            border-radius: 20px;
            padding: 6px 16px;
            font-size: 0.85rem;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .sheet-btn.active {
            background: rgba(65, 105, 225, 0.6);
            color: white;
            font-weight: 500;
        }

        .sheet-btn:hover:not(.active) {
            background: rgba(65, 105, 225, 0.4);
        }

        .table-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            flex-wrap: wrap;
            gap: 10px;
        }

        .table-stats {
            font-size: 0.9rem;
            color: #a3c5e7;
            background: rgba(255, 255, 255, 0.08);
            padding: 8px 15px;
            border-radius: 20px;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .empty-table {
            padding: 40px;
            text-align: center;
            color: #8cb3d9;
        }

        @media (max-width: 900px) {
            .form-wrapper {
                grid-template-columns: 1fr;
            }
        }

        @media (max-width: 600px) {
            .section {
                padding: 20px 15px;
            }

            .drag-area {
                height: 200px;
            }

            .drag-area h3 {
                font-size: 1.1rem;
            }

            .table-header {
                flex-direction: column;
                align-items: flex-start;
            }

            td {
                max-width: 300px;
                font-size: 0.9rem;
                padding: 8px 10px;
            }

            th {
                padding: 12px 10px;
                font-size: 0.9rem;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <header>
        <h1><i class="fas fa-file-excel"></i> Excel文件解析系统</h1>
        <p>上传Excel文件，实时解析并展示表格内容，支持数据预览与分析</p>
    </header>

    <div class="section">
        <div class="form-wrapper">
            <div class="input-group">
                <label for="name"><i class="fas fa-user"></i> 姓名</label>
                <input type="text" id="name" placeholder="请输入您的姓名">
            </div>

            <div class="input-group">
                <label for="age"><i class="fas fa-birthday-cake"></i> 年龄</label>
                <input type="number" id="age" placeholder="请输入您的年龄">
            </div>

            <div class="upload-section">
                <div class="drag-area">
                    <div class="icon">
                        <i class="fas fa-cloud-upload-alt"></i>
                    </div>
                    <h3>拖放或点击上传Excel文件</h3>
                    <span>支持.xlsx格式（最大10MB）</span>
                    <input type="file" id="fileInput" accept=".xlsx, .xls">
                </div>

                <div class="file-preview" id="filePreview">
                    <h4>准备上传:</h4>
                    <div id="fileName"></div>
                </div>

                <div class="progress-container" id="progressContainer">
                    <div class="progress-bar" id="progressBar"></div>
                </div>

                <div class="response-message" id="responseMessage"></div>

                <button class="btn-upload" id="uploadBtn" disabled>
                    <i class="fas fa-file-upload"></i> 开始上传
                </button>
            </div>
        </div>
    </div>

    <div class="section">
        <h2><i class="fas fa-table"></i> 解析结果</h2>

        <div id="excelControls" style="display: none; margin-top: 20px;">
            <div class="table-header">
                <div class="sheet-selector" id="sheetSelector"></div>
                <div class="table-stats" id="tableStats">
                    <i class="fas fa-table"></i>
                    <span>加载中...</span>
                </div>
            </div>
        </div>

        <div class="excel-container" id="excelContainer">
            <div class="excel-viewer">
                <table id="excelTable">
                    <thead class="sticky-header">
                    <tr id="tableHeader"></tr>
                    </thead>
                    <tbody id="tableBody"></tbody>
                </table>
            </div>
        </div>

        <div class="actions" id="actionsSection" style="display: none;">
            <button class="download-btn" id="downloadJsonBtn">
                <i class="fas fa-download"></i> 下载JSON数据
            </button>
            <button class="download-btn" id="downloadCsvBtn">
                <i class="fas fa-file-csv"></i> 导出CSV文件
            </button>
        </div>
    </div>

    <footer>
        <p>© 2023 Excel解析系统 | 基于Spring Boot和POI开发</p>
    </footer>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const dragArea = document.querySelector('.drag-area');
        const fileInput = document.getElementById('fileInput');
        const filePreview = document.getElementById('filePreview');
        const fileName = document.getElementById('fileName');
        const uploadBtn = document.getElementById('uploadBtn');
        const progressContainer = document.getElementById('progressContainer');
        const progressBar = document.getElementById('progressBar');
        const responseMessage = document.getElementById('responseMessage');
        const excelContainer = document.getElementById('excelContainer');
        const tableHeader = document.getElementById('tableHeader');
        const tableBody = document.getElementById('tableBody');
        const nameInput = document.getElementById('name');
        const ageInput = document.getElementById('age');
        const actionsSection = document.getElementById('actionsSection');
        const excelControls = document.getElementById('excelControls');
        const sheetSelector = document.getElementById('sheetSelector');
        const downloadJsonBtn = document.getElementById('downloadJsonBtn');
        const downloadCsvBtn = document.getElementById('downloadCsvBtn');
        const tableStats = document.getElementById('tableStats');

        let currentFile = null;
        let parsedData = null;
        let sheetNames = [];
        let currentSheetIndex = 0;
        let tableData = [];

        // 拖拽事件处理
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            dragArea.addEventListener(eventName, preventDefaults, false);
        });

        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }

        ['dragenter', 'dragover'].forEach(eventName => {
            dragArea.addEventListener(eventName, highlight, false);
        });

        ['dragleave', 'drop'].forEach(eventName => {
            dragArea.addEventListener(eventName, unhighlight, false);
        });

        function highlight() {
            dragArea.classList.add('active');
        }

        function unhighlight() {
            dragArea.classList.remove('active');
        }

        dragArea.addEventListener('drop', handleDrop, false);

        function handleDrop(e) {
            const dt = e.dataTransfer;
            const file = dt.files[0];
            handleFile(file);
        }

        // 文件选择处理
        fileInput.addEventListener('change', function() {
            if (this.files.length > 0) {
                handleFile(this.files[0]);
            }
        });

        function handleFile(file) {
            if (file) {
                // 验证文件类型
                const validTypes = [
                    'application/vnd.ms-excel',
                    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                ];

                if (!validTypes.includes(file.type)) {
                    showMessage('请上传有效的Excel文件（.xls 或 .xlsx）', 'error');
                    return;
                }

                // 验证文件大小
                if (file.size > 10 * 1024 * 1024) {
                    showMessage('文件大小不能超过10MB', 'error');
                    return;
                }

                // 更新文件预览
                currentFile = file;
                fileName.textContent = file.name;
                filePreview.classList.add('show');

                // 启用上传按钮
                uploadBtn.disabled = false;
            }
        }

        // 上传处理
        uploadBtn.addEventListener('click', uploadFile);

        function uploadFile() {
            if (!currentFile) {
                showMessage('请先选择要上传的文件', 'error');
                return;
            }

            // 禁用按钮，显示进度条
            uploadBtn.disabled = true;
            progressContainer.style.display = 'block';
            responseMessage.style.display = 'none';

            // 构建表单数据
            const formData = new FormData();
            formData.append('name', nameInput.value || '未命名');
            formData.append('age', ageInput.value || '0');
            formData.append('file', currentFile);

            // 模拟上传进度
            let progress = 0;
            const interval = setInterval(() => {
                progress += Math.random() * 10;
                if (progress > 95) {
                    clearInterval(interval);
                }
                progressBar.style.width = `${Math.min(progress, 95)}%`;
            }, 200);

            // 发送请求
            fetch('/upload', {
                method: 'POST',
                body: formData
            })
                .then(response => {
                    clearInterval(interval);
                    if (!response.ok) {
                        throw new Error('服务器响应错误');
                    }
                    return response.json();
                })
                .then(data => {
                    // 完成上传进度
                    progressBar.style.width = '100%';

                    // 解析成功的处理
                    parsedData = data.data;
                    sheetNames = data.sheetNames || ['Sheet1'];
                    tableData = data.tableData || [];

                    // 显示表格
                    showExcelData();
                    showMessage('文件解析成功！', 'success');

                    // 重置状态
                    setTimeout(() => {
                        progressContainer.style.display = 'none';
                        progressBar.style.width = '0%';
                        uploadBtn.disabled = false;
                    }, 1500);
                })
                .catch(error => {
                    clearInterval(interval);
                    showMessage(`上传失败: ${error.message}`, 'error');
                    progressContainer.style.display = 'none';
                    uploadBtn.disabled = false;
                    console.error('上传错误:', error);
                });
        }

        // 显示Excel数据
        function showExcelData() {
            if (!parsedData || parsedData.length === 0) {
                excelContainer.innerHTML = '<div class="empty-table">没有解析到数据</div>';
                return;
            }

            // 渲染表头
            tableHeader.innerHTML = '';
            if (parsedData[0].length > 0) {
                parsedData[0].forEach((cell, index) => {
                    const th = document.createElement('th');
                    th.textContent = cell || `列 ${index + 1}`;
                    tableHeader.appendChild(th);
                });
            }

            // 渲染表格数据
            tableBody.innerHTML = '';
            if (parsedData.length > 1) {
                for (let i = 1; i < parsedData.length; i++) {
                    const rowData = parsedData[i];
                    const row = document.createElement('tr');

                    rowData.forEach(cellValue => {
                        const cell = document.createElement('td');
                        if (typeof cellValue === 'object') {
                            cell.textContent = JSON.stringify(cellValue);
                        } else {
                            cell.textContent = cellValue;
                        }
                        row.appendChild(cell);
                    });

                    tableBody.appendChild(row);
                }
            } else {
                const row = document.createElement('tr');
                row.innerHTML = `<td colspan="${parsedData[0].length}" style="text-align:center">没有数据行</td>`;
                tableBody.appendChild(row);
            }

            // 更新表格统计信息
            updateStats();

            // 显示Excel查看器
            excelContainer.classList.add('show');
            actionsSection.style.display = 'flex';
            excelControls.style.display = 'block';

            // 更新Sheet选择器
            renderSheetSelector();
        }

        function updateStats() {
            if (!parsedData || parsedData.length < 2) {
                tableStats.innerHTML = '<i class="fas fa-table"></i> <span>0行 × 0列</span>';
                return;
            }

            const rows = parsedData.length - 1;
            const cols = parsedData[0].length;
            tableStats.innerHTML = `<i class="fas fa-table"></i> <span>${rows}行 × ${cols}列</span>`;
        }

        function renderSheetSelector() {
            if (!sheetNames || sheetNames.length === 0) return;

            sheetSelector.innerHTML = '';
            sheetNames.forEach((name, index) => {
                const button = document.createElement('button');
                button.className = 'sheet-btn';
                button.textContent = name;
                if (index === currentSheetIndex) {
                    button.classList.add('active');
                }

                button.addEventListener('click', () => {
                    document.querySelectorAll('.sheet-btn').forEach(btn => {
                        btn.classList.remove('active');
                    });
                    button.classList.add('active');
                    currentSheetIndex = index;

                    // 模拟切换sheet时的请求
                    showMessage(`已切换到工作表: ${name}`, 'success');

                    // 在真实环境中这里会向后端请求该sheet的数据
                    // fetchSheetData(currentSheetIndex);
                });

                sheetSelector.appendChild(button);
            });
        }

        // 消息显示函数
        function showMessage(message, type) {
            responseMessage.textContent = message;
            responseMessage.className = `response-message ${type}`;
            setTimeout(() => {
                responseMessage.style.opacity = '1';
            }, 100);

            if (type === 'error') {
                responseMessage.style.display = 'block';
            }
        }

        // 下载功能
        downloadJsonBtn.addEventListener('click', function() {
            if (!parsedData) {
                showMessage('没有数据可下载', 'error');
                return;
            }

            const jsonData = JSON.stringify(parsedData, null, 2);
            const blob = new Blob([jsonData], { type: 'application/json' });
            const url = URL.createObjectURL(blob);

            const a = document.createElement('a');
            a.href = url;
            a.download = `${currentFile.name.replace('.xlsx', '') || 'excel_data'}.json`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);

            showMessage('JSON文件已开始下载', 'success');
        });

        downloadCsvBtn.addEventListener('click', function() {
            if (!parsedData || parsedData.length === 0) {
                showMessage('没有数据可导出', 'error');
                return;
            }

            // 生成CSV内容
            const csvContent = parsedData.map(row => {
                return row.map(cell => {
                    // 处理特殊字符
                    let text = cell;
                    if (typeof cell === 'string') {
                        if (cell.includes('"') || cell.includes(',') || cell.includes('\n')) {
                            text = `"${cell.replace(/"/g, '""')}"`;
                        }
                    }
                    return text;
                }).join(',');
            }).join('\n');

            const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
            const url = URL.createObjectURL(blob);

            const a = document.createElement('a');
            a.href = url;
            a.download = `${currentFile.name.replace('.xlsx', '') || 'excel_data'}.csv`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);

            showMessage('CSV文件已开始下载', 'success');
        });
    });
</script>
</body>
</html>